<?php
/**
 * Created by PhpStorm.
 * User: 86188
 * Date: 2021/3/5
 * Time: 14:58
 */

namespace app\index\controller;


use think\Controller;
use think\Db;

class Wxuser extends Controller
{
    public function index(){
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx352362f198d9c56b&redirect_uri=http://www.wuye.zfbzhsq.com/index/wxuser/reg.html&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
        header("Location:".$url);
        exit;
    }
    public function reg(){
        $code = request()->get('code');
        $appid="wx352362f198d9c56b";
        $secret="891f9c8031c893848960d665e218f9ce";
        //用通过code换取网页授权access_token，同时获得openid
        $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
        $userinfo=$this->getJson($url);



        if($userinfo){
            session("user_id",$userinfo["openid"]);
            $access_token=(new Basewxget())->gettoken();
            $userurl="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$userinfo["openid"]."&lang=zh_CN";

            $result=file_get_contents($userurl);
            $res=json_decode($result,true);

            $wxuser=Db::table("zz_wxuser")->where("openid",$userinfo["openid"])->find();

            $user["headimgurl"]=$res["headimgurl"];
            $user["subscribe"]=$res["subscribe"];
            $user["nickname"]=$res["nickname"];
            $user["city"]=$res["city"];
            $user["province"]=$res["province"];
            $user["country"]=$res["country"];
            if(empty($wxuser)){
                $user["openid"]=$userinfo["openid"];
                Db::table("zz_wxuser")->insert($user);
                return "<div style='text-align: center;font-size:60px;margin-top:50px'>用户注册成功</div>";
            }else{
                $user["update_time"]=date("Y-m-d H:i:s");
                Db::table("zz_wxuser")->where("openid",$userinfo["openid"])->update($user);
                return "<div style='text-align: center;font-size:60px;margin-top:50px'>用户已注册</div>";
            }


        }else{
            return "<div style='text-align: center;font-size:60px;margin-top:50px'>获取用户信息失败</div>";

        }
    }
    function getJson($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($ch);
        curl_close($ch);
        return json_decode($output, true);
    }
}